package ui.fragment.homepagefragment;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.CommomDialog;
import adapter.AllNoticeAdapter;
import adapter.AllRankingAdapter;
import adapter.AllTimeTableAdapter;
import adapter.AllWorkAdapter;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.BuyRoomBean;
import bean.IndexBean;
import bean.JoinRoomBean;
import bean.ScheduleTableBean;
import bean.UnreadMsgBean;
import student.andlei.com.student.R;
import ui.activity.LiveBroadcastActivity;
import ui.activity.MainActivity;
import ui.activity.MessageActivity;
import ui.activity.PrePareTaskActivity;
import ui.activity.ReViewTaskActivity;
import ui.activity.VodActivity;
import ui.activity.WorkActivity;
import ui.fragment.HomePageFragment;
import ui.fragment.MineFragment;
import utils.DateUtils;
import utils.GlideUtils;
import utils.GsonUtils;
import utils.SPUtils;
import utils.TimeUtil;
import utils.ViewUtils;
import view.CircleImageView;

/**
 * 全部
 */
public class AllFragment extends BaseNetFragment {
    private RecyclerView rcly_timetable,
            rcly_class,
            rcly_work,
            rcly_notice;
    private TextView tv_date_week_time,
            tv_dayclass,
            tv_name,
            tv_school_class,
            tv_jifen,
            tv_paiming,
            tv_nofinish;
    public static CircleImageView img_head;
    private AllTimeTableAdapter timeTableAdapter;
    private AllRankingAdapter rankingAdapter;
    private AllWorkAdapter workAdapter;
    private AllNoticeAdapter noticeAdapter;
    private List<ScheduleTableBean.Rooms> timetable_list = new ArrayList<>();
    private List<IndexBean.ClassRank> rank_list = new ArrayList<>();
    private List<IndexBean.Task> work_list = new ArrayList<>();
    private List<IndexBean.Notice> notice_list = new ArrayList<>();
    private boolean isFirstMessage = true;

    public static Fragment getInstance() {
        return new AllFragment();
    }

    @Override


    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if (baseBean.code == 200) {
            if (action.equals("Schedule/joinRoom")) {
                JoinRoomBean joinRoomBean = (JoinRoomBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, JoinRoomBean.class);
                Bundle bundle = new Bundle();
                bundle.putString("chatroom_id", joinRoomBean.chatroom_id);
                bundle.putString("room_id", joinRoomBean.room_id+"");
                jumpTo(LiveBroadcastActivity.class, bundle);
            }else if(action.equals("personal/getUnreadMsg")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, UnreadMsgBean.class);
                if (bean.count == 0) {
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setVisibility(View.GONE);
                    MineFragment.tv_num.setVisibility(View.GONE);
                    //.setText(bean.msg_count+"");
                } else {
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setVisibility(View.VISIBLE);
                    MineFragment.tv_num.setVisibility(View.VISIBLE);
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setText(bean.count + "");
                    MineFragment.tv_num.setText(bean.count + "");
                }
            }else if(action.equals("schedule/buyRoom")){
                BuyRoomBean roomBean = (BuyRoomBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,BuyRoomBean.class);
                if(roomBean.status.equals("0")){
                    loadData();
                }else {
                    new CommomDialog(getActivity(), R.style.dialog, "课时不足，是否购买课时！", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                MainActivity.jumpToMineMyClassTime();
                                dialog.dismiss();
                            }
                        }
                    }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                }
            } else {
                IndexBean bean = (IndexBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, IndexBean.class);
                timetable_list = bean.rooms;
                rank_list = bean.classRank;
                work_list = bean.task;
                notice_list = bean.notice;
                if(isFirstMessage){
                    if(notice_list.size()>0){
                        notice_list.get(0).isNew = true;
                        isFirstMessage =false;
                    }
                }
                if (bean.msg_count == 0) {
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setVisibility(View.GONE);
                    MineFragment.tv_num.setVisibility(View.GONE);
                    //.setText(bean.msg_count+"");
                } else {
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setVisibility(View.VISIBLE);
                    MineFragment.tv_num.setVisibility(View.VISIBLE);
                    ((HomePageFragment) (this.getParentFragment())).tv_msg_num.setText(bean.msg_count + "");
                    MineFragment.tv_num.setText(bean.msg_count + "");
                }
                timeTableAdapter.setNewData(timetable_list);
                rankingAdapter.setNewData(rank_list);
                if (work_list != null) {
                    if (work_list.size() > 0) {
                        workAdapter.setNewData(work_list);
                    }
                }
                noticeAdapter.setNewData(notice_list);
                IndexBean.StudentInfo studentInfo = bean.studentInfo;
                GlideUtils.loadImageViewHeadphotoLoding(context, studentInfo.head_image, img_head);
                tv_name.setText(studentInfo.real_name);
                SPUtils.getInstance(context).put("name",studentInfo.real_name);
                SPUtils.getInstance(context).put("head_image",studentInfo.head_image);
                //学校审核状态 0没有学校 10待申请 20待审核 30审核失败 100通过
                if (studentInfo.school_status == 100) {
                    tv_school_class.setText(studentInfo.school_name+" "+studentInfo.schedule_name);
                } else {
                    tv_school_class.setText(studentInfo.grade_name);
                }

                tv_jifen.setText("积分：" + studentInfo.score);
                tv_paiming.setText("我的排名：" + bean.my_rank);
                String str_task = "未完成：<font color = \"#12B9A0\">" + bean.task_count + "</font>";
                tv_nofinish.setText(Html.fromHtml(str_task));
                String str_rooms_cont = "今日：<font color = \"#12B9A0\">" + bean.rooms_count + "</font>节课";
                tv_dayclass.setText(Html.fromHtml(str_rooms_cont));
            }
        } else {
            toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all;
    }

    @Override
    protected void findViews() {

        rcly_timetable = getView(R.id.rc_classtimetable_all);
        rcly_class = getView(R.id.rc_class_all);
        rcly_work = getView(R.id.rcly_work);
        rcly_notice = getView(R.id.rcly_notice);

        tv_date_week_time = getView(R.id.tv_date_all);
        tv_dayclass = getView(R.id.tv_courses_all);
        img_head = getView(R.id.iv_teacher_portrait_all);
        tv_name = getView(R.id.tv_student_name_all);
        tv_school_class = getView(R.id.tv_school_class_all);
        tv_jifen = getView(R.id.tv_jifen);
        tv_paiming = getView(R.id.tv_paiming);
        tv_nofinish = getView(R.id.tv_nofinish);
    }

    @Override
    protected void formatViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this.getActivity());
        GridLayoutManager layoutManager2 = new GridLayoutManager(this.getActivity(), 3);
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(this.getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        timeTableAdapter = new AllTimeTableAdapter(R.layout.item_alltimetable, timetable_list);
        //-----课表设置空布局-----------
        timeTableAdapter.setEmptyView(ViewUtils.GetEmptyView(context));
        rankingAdapter = new AllRankingAdapter(context, R.layout.item_allranking, rank_list);
        //-----班级排名设置空布局-----------
        rankingAdapter.setEmptyView(ViewUtils.GetClassEmptyView(context));

        workAdapter = new AllWorkAdapter(context, R.layout.item_allwork, work_list);
        noticeAdapter = new AllNoticeAdapter(R.layout.item_allnotice, notice_list);
        //----公告设置空布局------------
        noticeAdapter.setEmptyView(ViewUtils.GetNoticeEmptyView(context,"暂无公告"));
        rcly_timetable.setLayoutManager(layoutManager);
        rcly_class.setLayoutManager(layoutManager1);
        rcly_work.setLayoutManager(layoutManager2);
        rcly_notice.setLayoutManager(layoutManager3);
        rcly_timetable.setAdapter(timeTableAdapter);
        rcly_class.setAdapter(rankingAdapter);
        rcly_work.setAdapter(workAdapter);
        rcly_notice.setAdapter(noticeAdapter);
        timeTableAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.bt_look:
                        if(timetable_list.get(position).is_buy == 1){
                            new CommomDialog(getActivity(), R.style.dialog, "课外课时需要购买，消耗一课时！", new CommomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        Map<String,Object> map = new HashMap<>();
                                        map.put("room_id",""+timetable_list.get(position).room_id);
                                        post("schedule/buyRoom",map,BaseBean.class,false);
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                            return;
                        }
                        Button mbutton = (Button) view;
                        if (mbutton.getText().toString().trim().equals("查看录播")) {
                            switch (timetable_list.get(position).classroom_status) {
                                case 3:
                                    Bundle bundle = new Bundle();
                                    bundle.putString("media_type", "videoondemand");
                                    bundle.putString("decode_type", "software");
                                    // http://ohjdda8lm.bkt.clouddn.com/course/sample1.mp4  "http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/f50c3a97-98a7-4467-aefc-82089485e88c.flv"
                                    // http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/18c14535-b1e4-4a21-84d2-e560774df0ec.flv
                                    bundle.putString("videoPath", timetable_list.get(position).video);
                                    jumpTo(VodActivity.class, bundle);
                                    break;
                                case 4:
                                    new CommomDialog(getActivity(), R.style.dialog, "录播正在上传中，请稍等！", new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm) {
                                            if (confirm) {
                                                dialog.dismiss();
                                            }
                                        }
                                    }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                                    break;
                            }
                        } else if (mbutton.getText().toString().trim().equals("进入课堂")) {
                            switch (timetable_list.get(position).classroom_status) {
                                case 1:
                                    new CommomDialog(getActivity(), R.style.dialog, "课程尚未开始，请稍等！", new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm) {
                                            if (confirm) {
                                                dialog.dismiss();
                                            }
                                        }
                                    }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                                    break;
                                case 2:
                                    Map<String, String> map = new HashMap<>();
                                    map.put("room_id", "" + timetable_list.get(position).room_id);
                                    post("Schedule/joinRoom", map, BaseBean.class, true);
                                    break;
                            }
                        }
                        break;
                    case R.id.bt_state:
                        if(timetable_list.get(position).is_buy == 1){
                            new CommomDialog(getActivity(), R.style.dialog, "课外课时需要购买，消耗一课时！", new CommomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        Map<String,Object> map = new HashMap<>();
                                        map.put("room_id",""+timetable_list.get(position).room_id);
                                        post("schedule/buyRoom",map,BaseBean.class,false);
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                            return;
                        }
                        Button button = (Button) view;
                        if (button.getText().toString().trim().equals("预习")) {
                            if (timetable_list.get(position).bag_id == 0) {
                                new CommomDialog(getActivity(), R.style.dialog, "老师暂无备课包，无法进入预习任务", new CommomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                            } else {
                                //格式化时间
                                try{
                                    SimpleDateFormat CurrentTime= new SimpleDateFormat("HH:mm");
                                    Date beginTime  =   CurrentTime.parse(timetable_list.get(position).start_time);
                                    Date now =  CurrentTime.parse(DateUtils.getCurrentDatefour());
                                    Date endTime = CurrentTime.parse(timetable_list.get(position).end_time);
                                    if(beginTime.getTime()<now.getTime() && now.getTime()<endTime.getTime()){
                                        new CommomDialog(getActivity(), R.style.dialog, "课程已开始，点击进入课堂开始课程直播", new CommomDialog.OnCloseListener() {
                                            @Override
                                            public void onClick(Dialog dialog, boolean confirm) {
                                                if (confirm) {
                                                    dialog.dismiss();
                                                }
                                            }
                                        }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();

                                    }else {
                                        Bundle bundle_ = new Bundle();
                                        bundle_.putInt("room_id", timetable_list.get(position).room_id);
                                        jumpTo(PrePareTaskActivity.class, bundle_);
                                    }
                                }catch (Exception e){

                                }


                            }
                        } else {
                            if (timetable_list.get(position).bag_id == 0) {
                                new CommomDialog(getActivity(), R.style.dialog, "老师暂无备课包，无法进入复习任务", new CommomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                            } else {
                                Bundle bundle_ = new Bundle();
                                bundle_.putInt("room_id", timetable_list.get(position).room_id);
                                jumpTo(ReViewTaskActivity.class, bundle_);
                            }
                        }
                        break;
                }
            }
        });
        rankingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MainActivity.jumpToMineMyPoint();
            }
        });
        workAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(work_list.size()<=0){toast("暂无作业"); return;}
                Bundle bundle = new Bundle();
                bundle.putString("subject_id",work_list.get(position).subject_id+"");
                bundle.putString("subject_name",work_list.get(position).subject_name);
                jumpTo(WorkActivity.class,bundle);
            }
        });
        noticeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(notice_list.size()>0){
                    notice_list.get(0).isNew = false;
                }
                noticeAdapter.notifyDataSetChanged();
                Bundle bundle = new Bundle();
                bundle.putInt("noticeid",notice_list.get(position).id);
                jumpTo(MessageActivity.class,bundle);
            }
        });
    }

    @Override
    protected void formatData() {
//        for (int i = 0; i < 3; i++) {
//            AllTimeTableBean bean = new AllTimeTableBean();
//            AllRankingBean bean1 = new AllRankingBean();
        IndexBean.Task bean2 = new IndexBean.Task();
        IndexBean.Task bean21 = new IndexBean.Task();
        IndexBean.Task bean22 = new IndexBean.Task();
//            AllNoticeBean bean3 = new AllNoticeBean();
//            timetable_list.add(bean);
//            rank_list.add(bean1);
        bean2.subject_name = "语文";
        bean21.subject_name = "数学";
        bean22.subject_name = "英语";

        work_list.add(bean2);
        work_list.add(bean21);
        work_list.add(bean22);

//            notice_list.add(bean3);
        //   }
        tv_date_week_time.setText(DateUtils.getCurrentDateThree() + "  " + TimeUtil.getWeekOfDate(new Date()));
        loadData();
    }

    private void loadData() {
        post("personal/index", BaseBean.class, false);
    }

    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        post("personal/getUnreadMsg",BaseBean.class,false);
    }
}
